<template>
  <header>
    <div class="search-return" @click="goback">
        <i class="iconfont icon-fanhui"></i>
    </div>
    <div class="search-main">
        <i class="iconfont icon-fangdajing"></i>
        <form action="search" onsubmit="return false" @keyup.enter="goSearchList">
            <input class="linke" type="text" name="" id="" placeholder="搜索你喜欢的产品" v-model="searchValue"/>
        </form>
    </div>
    <div class="search-btn" @click="goSearchList">搜索</div>
  </header>
</template>

<script>

export default {
    data() {
        return{
            searchValue: this.$route.query.key || '',
            searCharr: []
        }
    },
    methods: {
        goback() {
            this.$router.back()
        },
        goSearchList() {
            
            // 如果搜索的关键字是没有的，那就直接return
            if(!this.searchValue) return
            // 判断之前有没有搜索的本地存储
            if(!localStorage.getItem('searchList')) {
                // 没有的情况下
                localStorage.setItem('searchList', '[]')
            } else {
                // 之前有的情况下
                this.searCharr = JSON.parse(localStorage.getItem('searchList'))
            }
            //增加数据
            this.searCharr.unshift(this.searchValue)
            // Es6去重
            let newArr = new Set(this.searCharr)
            // 给本地存储赋值
            localStorage.setItem('searchList', JSON.stringify(Array.from(newArr)))

            //路径没有变化， 不跳转
            if(this.searchValue === this.$route.query.key) return;

            // 跳转页面
            this.$router.push({
                name: 'list',
                query: {
                    key: this.searchValue
                }
            })
        }
    },
    created() {
        console.log()
    }
}
</script>

<style scoped>
    header {
        width: 100%;
        height: 1.1rem;
        display: flex;
        justify-content: space-around;
        align-items: center;
        background-color: #b0352f;
        color: #fff;
    }
    .search-return .search-btn{
        padding: 0 .2rem;
    }
    .search-return i{
        font-size: .56rem;
    }
    .search-main {
        display: flex;
        align-items: center;
        width: 7rem;
        height: .6rem;
        border-radius: 12px;
        background-color: #FFF;
    }
    .search-main i {
        color: #666666;
        padding: 0 .2rem;
    }
    .search-main form {
        display: flex;
        justify-content: center;
        align-items: center;
    }
    .search-btn {
        font-size: .34rem;
    }
    .linke {
        font-size: .4rem;
        color: #000;
    }
</style>